//
//  CCAFHTTPSessionManager.m
//  request
//
//  Created by cjg on 2018/5/30.
//  Copyright © 2018年 chenjg. All rights reserved.
//

#import "CCAFHTTPSessionManager.h"

@interface CCAFHTTPSessionManager ()

@property(nonatomic, strong) NSDictionary *requestTypeMap;

@end

@implementation CCAFHTTPSessionManager

- (NSDictionary *)requestTypeMap {
    if (!_requestTypeMap) {
        _requestTypeMap = @{
                @(RequestTypeGet): @"get",
                @(RequestTypePost): @"post",
        };
    }
    return _requestTypeMap;
}


- (NSURLSessionDataTask *)cc_ataTaskWithHTTPMethod:(RequestType)type
                                         URLString:(NSString *)URLString
                                        parameters:(id)parameters
                                    uploadProgress:(void (^)(NSProgress *))uploadProgress
                                  downloadProgress:(void (^)(NSProgress *))downloadProgress
                                           success:(void (^)(NSURLSessionDataTask *, id))success
                                           failure:(void (^)(NSURLSessionDataTask *, NSError *))failure {
    NSString *method = self.requestTypeMap[@(type)];
    if (!method) {
        return nil;
    }
    NSError *serializationError = nil;
    NSMutableURLRequest *request = [self.requestSerializer
            requestWithMethod:method
                    URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString]
                   parameters:parameters
                        error:&serializationError];
    if (serializationError) {
        if (failure) {
            dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
                failure(nil, serializationError);
            });
        }
        return nil;
    }
    __block NSURLSessionDataTask *dataTask = nil;
    dataTask = [self dataTaskWithRequest:request
                          uploadProgress:uploadProgress
                        downloadProgress:downloadProgress
                       completionHandler:^(NSURLResponse *__unused response, id responseObject, NSError *error) {
                           if (error) {
                               if (failure) {
                                   failure(dataTask, error);
                               }
                           } else {
                               if (success) {
                                   success(dataTask, responseObject);
                               }
                           }
                       }];
    return dataTask;
}

@end
